package com.bxl.index;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <>
 *
 * @author baixl
 * @date 2021/3/24
 */
public class TestFileSearch {
    public static void main(String[] args) {
        try {
            //将索引文件映射到内存
            RandomAccessFile file = new RandomAccessFile("D:\\home\\em_wf\\board\\log\\ai-index.index", "r");
            FileChannel channel = file.getChannel();
            MappedByteBuffer iBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            //将数据文件映射到内存。
            RandomAccessFile bFile = new RandomAccessFile("D:\\home\\em_wf\\board\\log\\ai-test.log", "r");
            FileChannel bChannel = bFile.getChannel();
            MappedByteBuffer bBuffer = bChannel.map(FileChannel.MapMode.READ_ONLY, 0, bChannel.size());

            //随机查找1000条数据
            Date start = new Date();
            for (int i = 0; i < 1000; i++) {
                Random random = new Random();
                int index = random.nextInt(100000);
                //计算key所在的槽
                int hash = Math.abs(("bxl" + index).hashCode()) % 10000;
                //hash槽的偏移量
                iBuffer.position(hash * 4);
                //索引条目的偏移量
                int indexOffset = iBuffer.getInt();
                //查找hash槽的所有物理偏移量
                List<Integer> phyOffsetList = new ArrayList();
                while (indexOffset > 0) {
                    iBuffer.position(indexOffset);
                    int phyOffset = iBuffer.getInt();
                    phyOffsetList.add(phyOffset);
                    indexOffset = iBuffer.getInt();
                }
                //根据物理偏移量到数据文件中取数据
                for (int j = 0; j < phyOffsetList.size(); j++) {
                    bBuffer.position(phyOffsetList.get(j));
                    byte[] content = new byte[bBuffer.getInt()];
                    bBuffer.get(content);
                    String mes = new String(content);
                    String key = mes.split(",")[0];
                    //key相等，输出消息内容i 是查询次数， index随机产生的数字
                    if (key.equals(("bxl" + index))) {
                        System.out.println(i + ":::" + index + "::::" + new String(content));
                    }

                }
            }

            Date end = new Date();
            System.out.println("usetime = "+(end.getTime()-start.getTime()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
